import json
import pandas as pd
import datetime
import requests
import sys

def func(data):
    # step2->处理数据
    # ---将json数组转化为dataframe
    df_json=pd.json_normalize(data,record_path=['data','result'])
    # ---取近12个自然月
    date_now = datetime.date.today()
    date_lastmth=date_now.replace(day=1) + datetime.timedelta(days=-1)
    date_lastyear=datetime.date(date_now.year-1,date_now.month,1)
    str_lastmth=date_lastmth.strftime("%Y%m")
    str_lastyear=date_lastyear.strftime("%Y%m")
    # ---筛选dataframe中符合条件的数据
    df_tmp=df_json[(df_json['sign']=='销项') & (df_json['zfbz']==False)
                & (df_json['ssyf']>=str_lastyear) & (df_json['ssyf']<=str_lastmth)]
    # ---对数据进行排序
    df_tmp.loc[:,'kprq']=pd.to_datetime(df_tmp['kprq'])
    df_tmp=df_tmp.sort_values(['kprq'],ascending=True)
    # ---向前取上一次开票日期
    df_tmp['last_kprq']=df_tmp['kprq'].shift()
    # ---加工时间间隔
    df_tmp['gap_days']=df_tmp['kprq']-df_tmp['last_kprq']

    # step3->输出结果
    print(df_tmp['gap_days'].max().days)

if __name__ == '__main__':
    # step1
    jsonStr = sys.argv[1]
    # 编写python 调用 java 数据网关的接口返回 数据
    result = json.loads(jsonStr)
    # result dict result的类型
    # 把字典转成字符串
    str = json.dumps(result)
    # 调用数据网关接口 得到结果
    url = 'http://zebra.dev.com/service-interface-gateway/api/invoke'
    header_dict = {"Content-Type": "application/json; charset=utf8"}
    r = requests.post(url, data=str, headers=header_dict)
    json_data = ''
    if (r.ok):
        json_data = r.json()
        func(json_data)